from django.contrib import admin
from django.utils.html import format_html
from django.db.models import Q, F
from django.utils.safestring import mark_safe
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.db import models
from .models import Category, Brand, Product, ProductImage


# 自定义过滤器
class StockLevelFilter(admin.SimpleListFilter):
    """库存水平过滤器"""
    title = '库存水平'
    parameter_name = 'stock_level'

    def lookups(self, request, model_admin):
        return (
            ('low', '低库存'),
            ('normal', '正常库存'),
            ('high', '高库存'),
            ('out', '缺货'),
        )

    def queryset(self, request, queryset):
        if self.value() == 'low':
            return queryset.filter(stock_quantity__lte=F('min_stock_level'))
        elif self.value() == 'normal':
            return queryset.filter(
                stock_quantity__gt=F('min_stock_level'),
                stock_quantity__lte=50
            )
        elif self.value() == 'high':
            return queryset.filter(stock_quantity__gt=50)
        elif self.value() == 'out':
            return queryset.filter(stock_quantity=0)


class DiscountFilter(admin.SimpleListFilter):
    """折扣过滤器"""
    title = '折扣情况'
    parameter_name = 'discount'

    def lookups(self, request, model_admin):
        return (
            ('has_discount', '有折扣'),
            ('no_discount', '无折扣'),
        )

    def queryset(self, request, queryset):
        if self.value() == 'has_discount':
            return queryset.filter(
                original_price__isnull=False,
                original_price__gt=F('price')
            )
        elif self.value() == 'no_discount':
            return queryset.filter(
                Q(original_price__isnull=True) |
                Q(original_price__lte=F('price'))
            )


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    """高级产品分类管理"""
    list_display = ('name', 'parent', 'products_count', 'is_active', 'sort_order', 'created_at')
    list_filter = ('is_active', 'parent', 'created_at')
    search_fields = ('name', 'description')
    list_editable = ('is_active', 'sort_order')
    ordering = ('sort_order', 'name')
    actions = ['activate_categories', 'deactivate_categories']

    def products_count(self, obj):
        """显示该分类下的产品数量"""
        count = obj.products.count()
        if count > 0:
            url = reverse('admin:products_product_changelist') + f'?category__id__exact={obj.id}'
            return format_html(
                '<a href="{}" style="color: #0066cc;">{} 个产品</a>',
                url, count
            )
        return '0 个产品'
    products_count.short_description = '产品数量'

    def activate_categories(self, request, queryset):
        updated = queryset.update(is_active=True)
        self.message_user(request, f'已激活 {updated} 个分类')
    activate_categories.short_description = '激活选中的分类'

    def deactivate_categories(self, request, queryset):
        updated = queryset.update(is_active=False)
        self.message_user(request, f'已禁用 {updated} 个分类')
    deactivate_categories.short_description = '禁用选中的分类'

    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'parent')
        }),
        ('设置', {
            'fields': ('is_active', 'sort_order')
        }),
    )


@admin.register(Brand)
class BrandAdmin(admin.ModelAdmin):
    """高级品牌管理"""
    list_display = ('name', 'logo_preview', 'products_count', 'is_featured', 'created_at')
    list_filter = ('is_featured', 'created_at')
    search_fields = ('name', 'description')
    list_editable = ('is_featured',)
    actions = ['mark_as_featured', 'mark_as_normal']

    def logo_preview(self, obj):
        if obj.logo:
            return format_html(
                '<img src="{}" style="width: 50px; height: 50px; object-fit: cover; border-radius: 5px;"/>',
                obj.logo.url
            )
        return format_html('<span style="color: #999;">无图片</span>')
    logo_preview.short_description = 'LOGO预览'

    def products_count(self, obj):
        """显示该品牌下的产品数量"""
        count = obj.products.count()
        if count > 0:
            url = reverse('admin:products_product_changelist') + f'?brand__id__exact={obj.id}'
            return format_html(
                '<a href="{}" style="color: #0066cc;">{} 个产品</a>',
                url, count
            )
        return '0 个产品'
    products_count.short_description = '产品数量'

    def mark_as_featured(self, request, queryset):
        updated = queryset.update(is_featured=True)
        self.message_user(request, f'已设置 {updated} 个品牌为精选')
    mark_as_featured.short_description = '设为精选品牌'

    def mark_as_normal(self, request, queryset):
        updated = queryset.update(is_featured=False)
        self.message_user(request, f'已取消 {updated} 个品牌的精选状态')
    mark_as_normal.short_description = '取消精选状态'


class ProductImageInline(admin.TabularInline):
    """产品图片内联编辑"""
    model = ProductImage
    extra = 1
    fields = ('image', 'alt_text', 'is_primary', 'sort_order')
    readonly_fields = ('image_preview',)

    def image_preview(self, obj):
        if obj.image:
            return format_html(
                '<img src="{}" style="width: 80px; height: 80px; object-fit: cover;"/>',
                obj.image.url
            )
        return '无图片'
    image_preview.short_description = '预览'


@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    """高级产品管理"""
    list_display = (
        'name', 'image_preview', 'category', 'brand', 'price_display',
        'stock_status', 'discount_info', 'status_colored', 'is_featured', 'created_at'
    )
    list_filter = (
        'status', 'is_featured', 'is_digital', 'category',
        'brand', StockLevelFilter, DiscountFilter, 'created_at'
    )
    search_fields = ('name', 'description', 'slug', 'brand__name', 'category__name')
    list_editable = ('status', 'is_featured')
    prepopulated_fields = {'slug': ('name',)}
    actions = [
        'mark_as_featured', 'unmark_as_featured',
        'activate_products', 'deactivate_products',
        'mark_as_out_of_stock'
    ]
    date_hierarchy = 'created_at'
    list_per_page = 20

    inlines = [ProductImageInline]

    # 高级搜索功能
    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super().get_search_results(request, queryset, search_term)
        try:
            # 支持按价格范围搜索，例如 "100-500"
            if '-' in search_term and len(search_term.split('-')) == 2:
                price_range = search_term.split('-')
                min_price = float(price_range[0])
                max_price = float(price_range[1])
                queryset |= self.model.objects.filter(
                    price__gte=min_price, price__lte=max_price
                )
        except ValueError:
            pass
        return queryset, use_distinct

    # 自定义显示方法
    def image_preview(self, obj):
        if obj.image:
            return format_html(
                '<img src="{}" style="width: 60px; height: 60px; object-fit: cover; border-radius: 8px;"/>',
                obj.image.url
            )
        return format_html('<span style="color: #999;">无图片</span>')
    image_preview.short_description = '图片'

    def price_display(self, obj):
        if obj.original_price and obj.original_price > obj.price:
            return format_html(
                '<span style="color: #e74c3c; font-weight: bold;">¥{}</span><br/>'
                '<span style="text-decoration: line-through; color: #999; font-size: 12px;">¥{}</span>',
                obj.price, obj.original_price
            )
        return format_html('<span style="font-weight: bold;">¥{}</span>', obj.price)
    price_display.short_description = '价格'

    def stock_status(self, obj):
        if obj.stock_quantity == 0:
            return format_html(
                '<span style="color: #e74c3c; font-weight: bold;">缺货</span>'
            )
        elif obj.is_low_stock:
            return format_html(
                '<span style="color: #f39c12; font-weight: bold;">{} (低库存)</span>',
                obj.stock_quantity
            )
        else:
            return format_html(
                '<span style="color: #27ae60;">{}</span>',
                obj.stock_quantity
            )
    stock_status.short_description = '库存状态'

    def discount_info(self, obj):
        discount = obj.discount_percentage
        if discount > 0:
            return format_html(
                '<span style="background: #e74c3c; color: white; padding: 2px 6px; border-radius: 3px; font-size: 11px;">-{}%</span>',
                discount
            )
        return '-'
    discount_info.short_description = '折扣'

    def status_colored(self, obj):
        colors = {
            'draft': '#6c757d',
            'active': '#28a745',
            'inactive': '#ffc107',
            'out_of_stock': '#dc3545',
        }
        status_names = {
            'draft': '草稿',
            'active': '在售',
            'inactive': '下架',
            'out_of_stock': '缺货',
        }
        color = colors.get(obj.status, '#6c757d')
        name = status_names.get(obj.status, obj.status)
        return format_html(
            '<span style="background: {}; color: white; padding: 3px 8px; border-radius: 4px; font-size: 12px;">{}</span>',
            color, name
        )
    status_colored.short_description = '状态'

    # 自定义批量操作
    def mark_as_featured(self, request, queryset):
        updated = queryset.update(is_featured=True)
        self.message_user(request, f'已设置 {updated} 个产品为精选')
    mark_as_featured.short_description = '设为精选产品'

    def unmark_as_featured(self, request, queryset):
        updated = queryset.update(is_featured=False)
        self.message_user(request, f'已取消 {updated} 个产品的精选状态')
    unmark_as_featured.short_description = '取消精选状态'

    def activate_products(self, request, queryset):
        updated = queryset.update(status='active')
        self.message_user(request, f'已激活 {updated} 个产品')
    activate_products.short_description = '激活产品'

    def deactivate_products(self, request, queryset):
        updated = queryset.update(status='inactive')
        self.message_user(request, f'已禁用 {updated} 个产品')
    deactivate_products.short_description = '禁用产品'

    def mark_as_out_of_stock(self, request, queryset):
        updated = queryset.update(status='out_of_stock', stock_quantity=0)
        self.message_user(request, f'已设置 {updated} 个产品为缺货状态')
    mark_as_out_of_stock.short_description = '设为缺货'

    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'slug', 'description', 'short_description')
        }),
        ('分类信息', {
            'fields': ('category', 'brand')
        }),
        ('价格信息', {
            'fields': ('price', 'original_price'),
            'classes': ('collapse',)
        }),
        ('库存信息', {
            'fields': ('stock_quantity', 'min_stock_level')
        }),
        ('图片信息', {
            'fields': ('image',)
        }),
        ('状态设置', {
            'fields': ('status', 'is_featured', 'is_digital')
        }),
        ('其他信息', {
            'fields': ('weight', 'dimensions'),
            'classes': ('collapse',)
        }),
    )


@admin.register(ProductImage)
class ProductImageAdmin(admin.ModelAdmin):
    """产品图片管理"""
    list_display = ('product', 'image_preview', 'alt_text', 'is_primary', 'sort_order')
    list_filter = ('is_primary', 'product__category')
    search_fields = ('product__name', 'alt_text')
    list_editable = ('is_primary', 'sort_order')

    def image_preview(self, obj):
        if obj.image:
            return format_html(
                '<img src="{}" style="width: 80px; height: 80px; object-fit: cover; border-radius: 5px;"/>',
                obj.image.url
            )
        return '无图片'
    image_preview.short_description = '图片预览'
